package com.ac.scum.log.web.model.wechat.mp.service;

import com.ac.scum.log.web.model.wechat.mp.mapper.WeChatUserMapper;
import com.ac.scum.wechat.bean.WeChatUser;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@AllArgsConstructor
public class AuthUserService {
    private final WxMpService wxService;
    private final WeChatUserMapper weChatUserMapper;

    public WeChatUser parseCode(String code) throws WxErrorException {
        boolean update = true;
        WxOAuth2AccessToken accessToken = wxService.getOAuth2Service().getAccessToken(code);
        WxOAuth2UserInfo user = wxService.getOAuth2Service().getUserInfo(accessToken, null);
        WeChatUser weChatUser = weChatUserMapper.selectByOpenId(user.getOpenid());
        if (weChatUser == null) {
            update = false;
            weChatUser = new WeChatUser();
        }
        weChatUser.setOpenId(user.getOpenid());
        weChatUser.setNickname(user.getNickname());
        weChatUser.setSex(user.getSex());
        weChatUser.setCity(user.getCity());
        weChatUser.setProvince(user.getProvince());
        weChatUser.setCountry(user.getCountry());
        weChatUser.setAvatar(user.getHeadImgUrl());
        weChatUser.setIsSubscribe(true);
        if (update) {
            weChatUserMapper.update(weChatUser, Wrappers.lambdaUpdate(WeChatUser.class).eq(WeChatUser::getOpenId, weChatUser.getOpenId()));

        } else weChatUserMapper.insert(weChatUser);
        return weChatUser;
    }
}
